package com.huwei.modules.base.intercept;

import java.util.Locale;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.LocaleResolver;

import com.huwei.modules.base.util.BeanUtil;
import com.huwei.modules.base.util.RedisUtil;  
  
/** 
 * 自定义国际化语言解析器 
 */
public class MyLocaleResolver implements LocaleResolver{  
      
    private static final String I18N_LANGUAGE = "i18n_language";  
    private static final String I18N_LANGUAGE_SESSION = "i18n_language_session";  
  
    @Autowired
    private RedisUtil redisUtil;
    
    @Override  
    public Locale resolveLocale(HttpServletRequest req) {  
        String i18n_language = req.getParameter(I18N_LANGUAGE);  
        Locale locale = Locale.getDefault();  
        if(Objects.nonNull(i18n_language)) {  
            String[] language = i18n_language.split("_");  
            locale = new Locale(language[0], language[1]);  
            //将国际化语言保存到session  
//            HttpSession session = req.getSession();  
//            session.setAttribute(I18N_LANGUAGE_SESSION, locale);
            //分布式系统建议换成到redis，避免多服务之间信息不同步问题；
            HttpSession session = req.getSession();
            String localeJsonString = BeanUtil.toJson(locale);
            redisUtil.opsForString().set((session.getId() + "#" + I18N_LANGUAGE_SESSION), localeJsonString,
            		15, TimeUnit.MINUTES);
        }else {  
            //如果没有带国际化参数，则判断session有没有保存，有保存，则使用保存的，也就是之前设置的，避免之后的请求不带国际化参数造成语言显示不对  
//            HttpSession session = req.getSession();  
//            Locale localeInSession = (Locale) session.getAttribute(I18N_LANGUAGE_SESSION);
//            if(localeInSession != null) {  
//                locale = localeInSession;  
//            }  
           //分布式系统建议换成到redis，避免多服务之间信息不同步问题；
           HttpSession session = req.getSession();  
           String localeJson = (String) redisUtil.opsForString().get(session.getId() + "#" + I18N_LANGUAGE_SESSION);
           Locale localeInRedis = BeanUtil.toBean(localeJson, Locale.class);
           if(Objects.isNull(localeInRedis)) {
        	   locale = localeInRedis;
           }
        }  
        return locale;  
    }  
  
    @Override  
    public void setLocale(HttpServletRequest req, HttpServletResponse res, Locale locale) {  
          
    }  
  
}  